package com.neshai.webapp.utils;

import org.web3j.utils.Numeric;
import org.web3j.crypto.Keys;
import org.web3j.crypto.Sign;

import java.math.BigInteger;

public class SignatureUtil {
    public static boolean verifySignature(String message, String signature, String address) {
        try {
            String prefixedMessage = "\u0019Ethereum Signed Message:\n" + message.length() + message;
            byte[] messageHash = prefixedMessage.getBytes();

            // 从签名中提取 r, s, v 值
            byte[] signatureBytes = Numeric.hexStringToByteArray(signature);
            byte v = signatureBytes[64];
            byte[] r = new byte[32];
            byte[] s = new byte[32];
            System.arraycopy(signatureBytes, 0, r, 0, 32);
            System.arraycopy(signatureBytes, 32, s, 0, 32);
            Sign.SignatureData signatureData = new Sign.SignatureData(v, r, s);
            // 计算签名的公钥
            BigInteger publicKey = Sign.signedMessageToKey(messageHash, signatureData);
            String recoveredAddress = "0x" + Keys.getAddress(publicKey);
            System.out.println(recoveredAddress);
            return address.equalsIgnoreCase(recoveredAddress);
        } catch (Exception e) {
            return false;
        }
    }

//    public static void main(String[] args) {
//        boolean a=verifySignature("Hello,sign this message!",
//                "0xa201a04439139169742a5d9de3700f91e8623ef18a850853738dc76c65f15506436162f49a1d9375d95bafe3ea6bebc070dd997d1a8105856a3f84518010476d1b",
//                "0x95467504E0C8B24e5748b91Ab79B5d5Ecd2e5516");
//        System.out.println(a);
//    }
}

